import { CHEESE_URL, OTHER_URL, ROUTERMAP, RPC_URL, VIDEO_URL } from "../constants";
import Message from "../message";

const getVideoInfo = async (
  url: string,
  filename: string
): Promise<[string, string]> => {
  try {
    const { data, result } = await fetch(url, {
      credentials: 'include'
    }).then(rdata => rdata.json());
    const durl = (data || result)?.durl[0].url;
    if (!durl) {
      throw new Error('durl is empty');
    }
    return [durl, filename + '.mp4'];
  } catch (e) {
    throw new Error('视频信息解析失败');
  }
}
const rpcHandler = (vinfos: [string, string][]) => {
  Message.success('视频信息解析成功')
  const header = [
    `User-Agent: ${navigator.userAgent}`,
    `Referer: ${location.href}`
  ];
  const data = vinfos.map(([url, out]) => {
    const param = { out, header };
    return {
      id: window.btoa(`BParse_${Date.now()}_${Math.random()}`),
      jsonrpc: '2.0',
      method: 'aria2.addUri',
      params: ['token:', [url], param]
    };
  });
  const request = {
    method: 'POST',
    body: JSON.stringify(data)
  }

  try {
    return fetch(RPC_URL, request);
  } catch (_) {
    throw new Error('RPC请求失败, 请开启Motrix');
  }
}

const getVideQuality = () => {
  const type = Object.keys(ROUTERMAP)
    .find(key => location.pathname.startsWith(ROUTERMAP[key])) || '?';
  if ('cheese' === type) {
    const cspan = <HTMLSpanElement>document.querySelector('div.edu-player-quality-item.active span');
    return cspan?.textContent || '80';
  }
  const selectid = 'video' === type
    ? 'li.bpx-player-ctrl-quality-menu-item.bpx-state-active'
    : 'li.squirtle-select-item.active';
  const cli = <HTMLLIElement>document.querySelector(selectid);
  return cli?.dataset?.value || '80';
}

const getVideUrl = () => {
  const type = Object.keys(ROUTERMAP)
    .find(key => location.pathname.startsWith(ROUTERMAP[key])) || '?';
  if ('cheese' === type) {
    return CHEESE_URL;
  }
  if ('video' === type || 'festival' === type) {
    return VIDEO_URL;
  }
  return OTHER_URL;
}

export default (videoDatas: VDInfoType[]) => {
  const par = new URLSearchParams({
    qn: getVideQuality(),
    fnver: '0',
    fnval: '0',
    fourk: '1',
    type: 'mp4',
    otype: 'json',
    platform: 'html5',
    high_quality: '1',
  });
  const reduceVideoInfo = videoDatas.map(({
    aid, bvid, cid, title, ep_id = ''
  }) => {
    par.set('avid', aid.toString());
    par.set('bvid', bvid);
    par.set('cid', cid.toString());
    par.set('ep_id', ep_id);
    return getVideoInfo([getVideUrl(), par.toString()].join('?'), title);
  });
  Promise.all(reduceVideoInfo).then(rpcHandler)
    .then(() => Message.success("RPC请求成功, 开始下载"))
    .catch(err => {
      console.warn(err);
      Message.error(err.message);
    });
}
